package ywu.tools.timesync;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class TimeSync extends Activity
{
    public static final String TAG = "ywu.TimeSync";

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("z yyyy-MM-dd HH:mm:ss.SSS");

    private TimeSyncService syncService = new TimeSyncService();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        Log.d(TAG, "Starting " + TAG);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // start sync service
        //        try
        //        {
        //            getApplicationContext().startService(new Intent(getApplicationContext(), TimeSyncService.class));
        //        }
        //        catch (Exception e)
        //        {
        //            Log.e(TAG, "start TimeSyncService failed", e);
        //        }

        final EditText txtServer = (EditText) findViewById(R.id.EditText_NtpServer);
        final Button btnSyncNow = (Button) findViewById(R.id.Btn_SyncNow);
        final TextView txtMsg = (TextView) findViewById(R.id.Txt_Msg);

        btnSyncNow.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v)
            {
                String server = txtServer.getText().toString().trim();

                Date sysTime = new Date();
                Date ntwTime = getSyncService().syncSysTime(server);

                updateMessage(ntwTime, sysTime, txtMsg);
            }
        });
        updateSyncBtn(txtServer, btnSyncNow);

        txtServer.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(final CharSequence s, final int start, final int before, final int count)
            {
                updateSyncBtn(txtServer, btnSyncNow);
            }

            @Override
            public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after)
            {
                // ignore
            }

            @Override
            public void afterTextChanged(final Editable s)
            {
                // ignore
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);

        return true;
    }

    /**
     * Handles item selections
     */
    @Override
    public boolean onOptionsItemSelected(final MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.menu_exit:
                System.exit(0);
                return true;
        }
        return true;
    }

    public TimeSyncService getSyncService()
    {
        return syncService;
    }

    public void setSyncService(final TimeSyncService syncService)
    {
        this.syncService = syncService;
    }

    protected void updateSyncBtn(final EditText txtServer, final Button btnSyncNow)
    {
        String txt = txtServer.getText().toString().trim();
        btnSyncNow.setEnabled(txt.length() > 0);
    }

    protected void updateMessage(final Date ntwTime, final Date sysTime, final TextView txtMsg)
    {
        if (ntwTime == null)
        {
            txtMsg.setText("Internet time synchronization failed, please check the network.");
            return;
        }

        StringBuilder buf = new StringBuilder("Internet time:\n");
        buf.append(DATE_FORMAT.format(ntwTime));
        buf.append("\n\nLast sync at:\n").append(DATE_FORMAT.format(sysTime));
        txtMsg.setText(buf.toString());
    }

}
